package com.yh.ldzl.service;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.yh.ldzl.feign.ProductionModuleClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 质检结果通知服务
 * 负责将质检结果通知给生产模块
 * 
 * @author ldzl
 * @date 2025-01-23
 */
@Service
public class QualityCheckNotificationService {

    @Autowired
    private ProductionModuleClient productionModuleClient;

    /**
     * 通知生产模块质检完成
     *
     * @param taskId 任务ID（从检验单的来源信息中获取）
     * @param qualityCheckId 质检单ID
     * @param checkResult 质检结果 (1=合格, 2=不合格, 3=待检)
     * @param qualifiedQty 合格数量
     * @param unqualifiedQty 不合格数量
     * @param remarks 备注信息
     * @param sourceDocType 源单据类型
     * @param qualityCheckType 质检类型
     */
    public void notifyProductionModule(Long taskId, Long qualityCheckId, String checkResult,
                                     BigDecimal qualifiedQty, BigDecimal unqualifiedQty, String remarks,
                                     String sourceDocType, String qualityCheckType) {
        try {
            System.out.println("=== 通知生产模块质检完成 ===");
            System.out.println("任务ID: " + taskId);
            System.out.println("质检单ID: " + qualityCheckId);
            System.out.println("质检结果: " + checkResult);
            System.out.println("合格数量: " + qualifiedQty);
            System.out.println("不合格数量: " + unqualifiedQty);
            System.out.println("质检类型: " + qualityCheckType);
            System.out.println("源单据类型: " + sourceDocType);

            // 构建回调数据
            Map<String, Object> callbackData = new HashMap<>();
            callbackData.put("taskId", taskId);
            callbackData.put("qualityCheckId", qualityCheckId);
            callbackData.put("checkResult", checkResult);
            callbackData.put("qualifiedQty", qualifiedQty);
            callbackData.put("unqualifiedQty", unqualifiedQty);
            callbackData.put("totalQty", qualifiedQty.add(unqualifiedQty != null ? unqualifiedQty : BigDecimal.ZERO));
            callbackData.put("remarks", remarks);
            callbackData.put("timestamp", System.currentTimeMillis());
            // 添加质检类型和源单据类型
            callbackData.put("sourceDocType", sourceDocType);
            callbackData.put("qualityCheckType", qualityCheckType);

            // 使用Feign客户端发送回调请求
            AjaxResult result = productionModuleClient.qualityCheckCallback(callbackData);

            if (result != null && result.isSuccess()) {
                System.out.println("质检结果通知发送成功: " + result.get("msg"));
            } else {
                System.err.println("质检结果通知发送失败: " + (result != null ? result.get("msg") : "返回为空"));
            }

        } catch (Exception e) {
            System.err.println("发送质检结果通知异常: " + e.getMessage());
            e.printStackTrace();

            // 这里可以考虑重试机制或者记录到失败队列
            // TODO: 实现重试机制
        }
    }

    /**
     * 通知生产模块质检完成 (兼容旧方法)
     *
     * @param taskId 任务ID
     * @param qualityCheckId 质检单ID
     * @param checkResult 质检结果
     * @param qualifiedQty 合格数量
     * @param unqualifiedQty 不合格数量
     * @param remarks 备注信息
     */
    public void notifyProductionModule(Long taskId, Long qualityCheckId, String checkResult,
                                     BigDecimal qualifiedQty, BigDecimal unqualifiedQty, String remarks) {
        // 默认使用null值调用带类型参数的方法
        notifyProductionModule(taskId, qualityCheckId, checkResult, qualifiedQty, unqualifiedQty, remarks, null, null);
    }

    /**
     * 通知质检进度更新
     *
     * @param taskId 任务ID
     * @param qualityCheckId 质检单ID
     * @param progress 进度状态 (created=已创建, in_progress=进行中, completed=已完成)
     * @param message 进度消息
     */
    public void notifyQualityCheckProgress(Long taskId, Long qualityCheckId, String progress, String message) {
        try {
            System.out.println("=== 通知质检进度更新 ===");
            System.out.println("任务ID: " + taskId);
            System.out.println("质检单ID: " + qualityCheckId);
            System.out.println("进度: " + progress);
            System.out.println("消息: " + message);

            // 构建进度数据
            Map<String, Object> progressData = new HashMap<>();
            progressData.put("taskId", taskId);
            progressData.put("qualityCheckId", qualityCheckId);
            progressData.put("progress", progress);
            progressData.put("message", message);
            progressData.put("timestamp", System.currentTimeMillis());

            // 使用Feign客户端发送进度通知
            AjaxResult result = productionModuleClient.qualityCheckProgress(progressData);

            if (result != null && result.isSuccess()) {
                System.out.println("质检进度通知发送成功: " + result.get("msg"));
            } else {
                System.err.println("质检进度通知发送失败: " + (result != null ? result.get("msg") : "返回为空"));
            }

        } catch (Exception e) {
            System.err.println("发送质检进度通知异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 从检验单中提取任务ID
     * 根据检验单的来源信息提取对应的任务ID
     * 
     * @param sourceDocId 来源单据ID
     * @param sourceDocType 来源单据类型
     * @return 任务ID
     */
    public Long extractTaskIdFromSource(Long sourceDocId, String sourceDocType) {
        if ("WORK_ORDER_TASK".equals(sourceDocType)) {
            return sourceDocId; // 直接返回任务ID
        }
        
        // 其他类型的来源单据处理逻辑
        // TODO: 根据实际业务需求扩展
        
        return sourceDocId;
    }

    /**
     * 验证回调数据的完整性
     */
    private boolean validateCallbackData(Long taskId, Long qualityCheckId, String checkResult) {
        if (taskId == null || taskId <= 0) {
            System.err.println("任务ID无效: " + taskId);
            return false;
        }
        
        if (qualityCheckId == null || qualityCheckId <= 0) {
            System.err.println("质检单ID无效: " + qualityCheckId);
            return false;
        }
        
        if (checkResult == null || (!checkResult.equals("1") && !checkResult.equals("2") && !checkResult.equals("3"))) {
            System.err.println("质检结果无效: " + checkResult);
            return false;
        }
        
        return true;
    }
}
